package com.zyx.jwt.util;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import com.zyx.jwt.common.CommonConstant;
import com.zyx.jwt.entity.JwtInfo;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

/**
 * @author Yaxi.Zhang
 * @since 2022/9/11 14:29
 */
public class JwtUtils {
    /**
     * 私钥生成token
     */
    public static String generateToken(JwtInfo jwtInfo, byte[] priKey, int expire) throws Exception {
        return Jwts.builder()
                .setSubject(jwtInfo.getUniqueName())
                .claim(CommonConstant.JWT_KEY_USER_ID, jwtInfo.getId())
                .claim(CommonConstant.JWT_KEY_NAME, jwtInfo.getName())
                .claim(CommonConstant.JWT_KEY_ACCOUNT_TYPE, jwtInfo.getType())
                .setExpiration(DateTime.now().offset(DateField.SECOND, expire).toJdkDate())
                .signWith(RsaKeyHelper.getPrivateKey(priKey), SignatureAlgorithm.RS256)
                .compact();
    }

    /**
     * 公钥解析token
     */
    public static Jws<Claims> parseToken(String token, byte[] pubKey) throws Exception {
        return Jwts.parserBuilder().setSigningKey(RsaKeyHelper.getPublicKey(pubKey)).build().parseClaimsJws(token);
    }

}
